package com.us.usws.batch.resimp.region;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import net.iwsh.core.exception.GenericRuntimeException;
import net.iwsh.core.utils.IDGenerator;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.supercsv.cellprocessor.constraint.NotNull;
import org.supercsv.cellprocessor.ift.CellProcessor;

import com.us.usws.batch.BatchUtils;
import com.us.usws.batch.resimp.BatchBdao;
import com.us.usws.batch.resimp.ResImpAbstractWorker;
import com.us.usws.batch.resimp.result.FailureCellResult;
import com.us.usws.batch.resimp.result.ResImpResult;
import com.us.usws.common.SiteConstants;
import com.us.usws.model.domain.base.BaseDict;

public class CSVRegionImpWorker extends ResImpAbstractWorker<CSVRegion> {

	private static Log log = LogFactory.getFactory().getInstance(CSVRegionImpWorker.class);

	private static final String[] headers = new String[] { "code", "name" };

	private Date now = new Date();

	@Override
	public CellProcessor[] getProcessors() {

		final CellProcessor[] processors = new CellProcessor[] { new NotNull(), // code
				new NotNull() // name
		};

		return processors;
	}

	@Override
	public String[] getHeaders() {
		return headers;
	}

	@Override
	public ResImpResult imp() {
		List<CSVRegion> res = getResults();
		if (res == null) {
			throw new GenericRuntimeException("Please load csv first.");
		}

		//loop 1st, get top channels
		int idx = 0;
		ResImpResult ret = new ResImpResult();
		ret.setTitle("导入行政区划代码");
		List<BaseDict> dicts = new ArrayList<>();
		for (CSVRegion each : res) {
			idx++;
			String code = each.getCode();
			String name = each.getName();

			BaseDict one = new BaseDict();
			one.setCode(code);
			one.setCreateByUid(BatchUtils.ADMIN_UID);
			one.setCreateDate(now);
			one.setDomain(SiteConstants.DICT_DOMAIN_REGION);
			//one.setExtraVal(extraVal);
			one.setName(name);
			one.setSepId(idx);
			one.setSeqNum(idx);
			one.setUid(IDGenerator.getInstance().genUID());
			dicts.add(one);
		}

		BatchBdao dao = new BatchBdao();
		try {
			dao.createRegionsIntoDict(dicts);
			ret.setSuccessCnt(dicts.size());
			ret.setSummaryMsg("导入成功。");
		} catch (Exception e) {
			log.error("create regions failed.", e);
			ret.getFailures().add(new FailureCellResult("所有", 0, 0, "保存失败。"));
		}

		return ret;
	}
}
